package com.maslyk.invitation.utils;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import com.maslyk.configuration.ConfigurationManager;
import com.maslyk.invitation.exception.SystemException;
import com.maslyk.invitation.to.SimpleProduct;

public class ExcelDataProvider {

	public static List<SimpleProduct> getProductList(String sheetName) throws SystemException {

		List<SimpleProduct> productList = new ArrayList<SimpleProduct>();
		try {

			ConfigurationManager.getInstance().getProductDatasourceFileUrl();

			URL url = new URL(ConfigurationManager.getInstance().getProductDatasourceFileUrl());
			url.openConnection();
			InputStream inp = url.openStream();

			Workbook wb;

			wb = WorkbookFactory.create(inp);

			Sheet sh = wb.getSheet(sheetName);

			for (Row row : sh) {

				String name = row.getCell(0).getRichStringCellValue().getString();
				double netAmount = row.getCell(1).getNumericCellValue();
				double totalAmount = row.getCell(2).getNumericCellValue();
				productList.add(new SimpleProduct(name, netAmount, totalAmount));
			}

			inp.close();

		} catch (Exception e) {
			throw new SystemException(e);
		}

		return productList;
	}
}
